import glob
import os
import re
from pathlib import Path


def increment_path(path, exist_ok=False, sep='', mkdir=False):
    # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
    path = Path(path)  # os-agnostic
    stem = path.stem
    folder = str(path.parent)
    suffix = path.suffix
    if path.exists() and not exist_ok:
        # print("stem:",stem)
        match_obj = re.split(r'(\d+$)', stem, re.M | re.I)
        # print("match_obj", match_obj)
        if len(match_obj) == 1:
            start = 1
        elif len(match_obj) > 1:
            start = int(match_obj[1])
        stem = match_obj[0]
        for n in range(start, 9999):
            p = f'{folder}/{stem}{sep}{n}{suffix}'  # increment path
            if not os.path.exists(p):  #
                break
        path = Path(p)

    if mkdir:
        path.mkdir(parents=True, exist_ok=True)  # make directory

    return path


def take_number(str_name):
    pat = r'\d*$'
    result = re.search(pat, str_name)

    if result is None or result.group()=='':
        return 0
    else:
        return  int(result.group())



def last_path(folder, ext='*.pt'):
    # root, dirs, files = os.walk
    dirs = os.listdir(folder)
    valids = [d for d in dirs if ext in d]
    valids.sort(key=take_number)
    print(valids)

    # sorted(valids, key=os.path.getmtime)
    return valids[-1]


if __name__ == '__main__':
    a='sdfs1df1'
    print(take_number(a))
